package ez

import (
	"encoding/json"
	"fmt"
	"time"
)

type Timer struct {
	Start   int64
	End     int64
	Process []*Process
}

func NewTimer() *Timer {
	return &Timer{
		Start: time.Now().UnixMicro(),
	}
}

func (this *Timer) Done() {
	this.End = time.Now().UnixMicro()
}
func (this *Timer) Add(name string) *Process {
	process := &Process{Name: name, Start: time.Now().UnixMicro()}
	this.Process = append(this.Process, process)
	return process
}
func (this *Timer) Report() {
	data, e := json.MarshalIndent(this, "", "\t")
	if e != nil {
		println("Timer.Report", e.Error())
	}
	print("\n-----------------------\n")
	print(string(data))
	print("\n-----------------------\n")
}

type Process struct {
	Name       string
	Start      int64
	End        int64
	Cost       int64
	CostString string
	Note       string
}

func (this *Process) Done(message ...string) {
	if this.End == 0 {
		this.End = time.Now().UnixMicro()
		this.Cost = this.End - this.Start
		if this.Cost > 1000000 {
			//秒
			this.CostString = fmt.Sprintf("%.3fs", float64(this.Cost)/1000000)
		} else {
			//毫秒
			this.CostString = fmt.Sprintf("%.3fms", float64(this.Cost)/1000)
		}
		if len(message) > 0 {
			this.Note = message[0]
		}
	}
}
